package com.jike.noobmoney.mvp.presenter;


import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.net.ApiStore;
import com.jike.noobmoney.net.HttpClient;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by kekex on 2019/2/28.
 * basepresenter
 */

public class BasePresenter<T> implements Presenter<T> {

    public T iView;
    protected ApiStore iHttpUrl = HttpClient.getRetrofit(ConstantValue.BASEURL).create(ApiStore.class);
    private CompositeSubscription compositeSubscription;

    public BasePresenter(T view) {
        attachView(view);
    }

    /**
     * 绑定接口
     */
    @Override
    public void attachView(T view) {
        this.iView = view;
    }

    @Override
    public void detachView() {
        this.iView = null;
        onUnsubscribe();
    }

    /**
     * rxjava取消注册，以避免内存泄漏
     */
    public void onUnsubscribe() {
        if (compositeSubscription != null && compositeSubscription.hasSubscriptions()) {
            compositeSubscription.unsubscribe();
        }
    }

    /**
     * 进行网络请求
     */
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (compositeSubscription == null) {
            compositeSubscription = new CompositeSubscription();
        }
        compositeSubscription.add(observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber));
    }


}
